package reese.think_in_java.java_21_thread;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * ***********************************************************
 *
 * @类名 : reese.think_in_java.java_21_thread.类名
 * @DESCRIPTION : 这家伙太懒啥都没写
 * @AUTHOR :  一个风情万种的男子
 * @DATE : 2016/5/31
 * ***********************************************************
 */
public class AttemptLocking {

    private ReentrantLock lock = new ReentrantLock();

    public void  untimed(){
        boolean captured = lock.tryLock();
        try {
            System.out.println("tryLock():" + captured);

        }finally {
            if(captured){
                lock.unlock();
            }
        }
    }

    public void timed(){
        boolean captured = false ;
        try {
            captured = lock.tryLock(2, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            throw  new RuntimeException(e);
        }
        try {
            System.out.println("tryLock(2,TimeUnit.SECONDS):" + captured);
        }finally {
            if (captured){
                lock.unlock();
            }
        }

    }

    public static void main(String[] args) {
        final AttemptLocking al =  new AttemptLocking();
        al.untimed();
        al.timed();
        //now create a separate task to grab the lock 分离  抢占
         new Thread(){
             {
                 setDaemon(true);
             }

             @Override
             public void run() {
                 al.lock.lock();
                 System.out.println("acquired--回收");
             }
         }.start();

        Thread.yield(); // Give the 2nd Task  a chance
        al.untimed();
        al.timed();

    }
}
